package com.xiaozeng.cart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaozeng.cart.mapper.CartMapper;
import com.xiaozeng.cart.service.CartService;
import com.xiaozeng.clients.ProductClient;
import com.xiaozeng.param.CartParam;
import com.xiaozeng.param.ProductCollectParam;
import com.xiaozeng.pojo.Cart;
import com.xiaozeng.pojo.Product;
import com.xiaozeng.pojo.User;
import com.xiaozeng.utils.Result;
import com.xiaozeng.vo.CartVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: xiaozeng
 * @Date: 2022 11
 * @Description:
 **/
@Service
@Slf4j
public class CartServiceImpl extends ServiceImpl<CartMapper,Cart> implements CartService{
    @Autowired
    private ProductClient productClient;
    @Autowired
    private CartMapper cartMapper;
    @Override
    public Result save(CartParam cartParam) {
        User user =(User) SecurityUtils.getSubject().getPrincipal();
        //查询关联的商品信息 复用商品集合查询
        List<Integer> ids = new ArrayList<>();
        ids.add(cartParam.getProductId());
        ProductCollectParam productCollectParam = new ProductCollectParam();
        productCollectParam.setProductIds(ids);
        Product product = productClient.ids(productCollectParam).get(0);

        if (product == null){
            log.info("CartServiceImpl.save业务开始，添加失败!");
            return Result.fail("商品添加购物车失败!");
        }
        //1.检查是否已经达到最大库存

        int productNum = product.getProductNum();
        if (productNum == 0){
            Result fail = Result.fail("已经没有库存,无法购买!");
            fail.setCode("003"); //没有库存的错误码
            return fail;
        }
        //2.检查是不是第一次添加
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getUserId());
        queryWrapper.eq("product_id",cartParam.getProductId());

        if (cartMapper.exists(queryWrapper)){
            //不是第一次,直接返回已经添加过即可!
            //更新属性 + 1
            Cart cart = cartMapper.selectOne(queryWrapper);
            cart.setNum(cart.getNum()+1);
            cartMapper.updateById(cart);
            Result ok = Result.ok("商品已经在购物车,数量+1!");
            ok.setCode("002");
            return ok;
        }
        //是第一次
        Cart cart = new Cart();
        cart.setNum(1);
        cart.setProductId(cartParam.getProductId());
        cart.setUserId(user.getUserId());
        cartMapper.insert(cart);
        //结果封装
        CartVo cartVo = new CartVo(product,cart);
        log.info("CartServiceImpl.save业务结束，结果:{}",cartVo);
        return Result.ok(cartVo);
    }

    public Result cartList() {
        User user =(User) SecurityUtils.getSubject().getPrincipal();
        //查询用户id对应的购物车数据
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getUserId());
        List<Cart> cartList = cartMapper.selectList(queryWrapper);

        //判断购物车是否为空
        if (cartList == null || cartList.size() == 0){
            return Result.ok("购物车没有数据!",cartList);
        }

        //封装商品集合,查询商品数据
        List<Integer> ids = new ArrayList<>();
        for (Cart cart : cartList) {
            ids.add(cart.getProductId());
        }
        ProductCollectParam productCollectParam = new ProductCollectParam();
        productCollectParam.setProductIds(ids);
        List<Product> productList = productClient.ids(productCollectParam);

        //cartList和productList结果封装到Vo里
        //为了能把cartList里的商品id和Product一一对应，将productList集合转map
        //jdk8 的 stream
        Map<Integer, Product> map = productList.stream().
                collect(Collectors.toMap(Product::getProductId, v -> v));
        System.out.println("map = " + map);

        //结果封装即可
        List<CartVo> list = new ArrayList<>(cartList.size());
        for (Cart cart : cartList) {
            CartVo cartVo = new CartVo(map.get(cart.getProductId()),cart);
            list.add(cartVo);
        }

        Result ok = Result.ok(list);
        log.info("CartServiceImpl.list业务结束，结果:{}",ok);
        return ok;
    }

    @Override
    public Result remove(CartParam cartParam) {
        User user =(User) SecurityUtils.getSubject().getPrincipal();
        //删除参数封装
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getUserId());
        queryWrapper.eq("product_id",cartParam.getProductId());
        //删除数据
        cartMapper.delete(queryWrapper);
        return Result.ok("删除数据成功!");
    }
}
